package com.hddf.project.auth.dao_impl;

import java.util.Map;

import org.bson.types.ObjectId;
import org.kommii.common_utils.DateTime_Utils;

import com.hddf.project.auth.dao.KeyPairDao_MongoDB;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.QueryBuilder;
import com.mongodb.WriteConcern;

public class KeyPairDaoImpl_MongoDB implements KeyPairDao_MongoDB{
	
	//密钥对的有效时间 单位是秒
	public static final int keyPair_validTime = 60*5;

	public String add(String pubk, Map map,DBCollection coll) {
		long current = DateTime_Utils.getCurrentSeconds();
		BasicDBObject entity = new BasicDBObject();
		entity.put("pubk", pubk);
		entity.put("prik_map",map);
		entity.put("keypair_deadline", current+keyPair_validTime);
		coll.save(entity, WriteConcern.SAFE);
		String rs = ((ObjectId)entity.get("_id")).toString();
		return rs;
	}

	public boolean delete(String id,DBCollection coll) {
		ObjectId oid = new ObjectId(id);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query = queryBuilder.put("_id").is(oid).get();
		//使用 findAndRemove 方法会把被删除的对象返回 
		DBObject obj = coll.findAndRemove(query);
		if(null!=obj)
			return true;
		else
			return false;
	}

	public DBObject getById(String id,DBCollection coll) {
		ObjectId oid = new ObjectId(id);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query = queryBuilder.put("_id").is(oid).get();
		DBObject entity = coll.findOne(query);
		return entity;
	}
	
	public DBObject getPriKeyById(String id,DBCollection coll){
		ObjectId oid = new ObjectId(id);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query = queryBuilder.put("_id").is(oid).get();
		BasicDBObject key = new BasicDBObject("prik_map",1).append("_id", 0);
		DBObject entity = coll.findOne(query,key);
		return entity;
	}
	
	public DBObject getPubKeyById(String id, DBCollection coll){
		ObjectId oid = new ObjectId(id);
		QueryBuilder queryBuilder = QueryBuilder.start();
		DBObject query = queryBuilder.put("_id").is(oid).get();
		BasicDBObject key = new BasicDBObject("pubk",1).append("_id", 0);
		DBObject entity = coll.findOne(query,key);
		return entity;
	}

}
